const co = require('co')
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const querystring = require('querystring')

const proxy = require('./proxy')
const conf = require('./conf')

// 问卷星
const WJX = {}

WJX.getQuestion = function(id) {
    return function(cb) {
        co(function*() {
            let ret = yield proxy.GET('/m/' + id + '.aspx?from=singlemessage#')
            let cookies = []
            for (i in ret.headers['set-cookie']) {
                cookies.push(ret.headers['set-cookie'][i].split('; ')[0])
            }
            let $ = cheerio.load(ret.body)
            let questions = []
            let answers = []
            $('.req').remove()
            $('.ui-field-contain').each(function() {
                if ($(this).attr('type') == '3') {
                    let question = {
                        _: $(this).find('.field-label').text()
                    }
                    $(this).find('.ui-radio').each(function() {
                        let answer = $(this).find('.label').text()
                        if (answer.startsWith('①')) {
                            question._ += answer
                        } else if (answer.startsWith('A.')) {
                            question.A = answer
                        } else if (answer.startsWith('B.')) {
                            question.B = answer
                        } else if (answer.startsWith('C.')) {
                            question.C = answer
                        } else if (answer.startsWith('D.')) {
                            question.D = answer
                        }
                    })
                    questions.push(question)
                    let t = $(this).attr('topic')
                    answers.push(`${t}$2`) // 全部选B交卷
                }
            })
            let submitdata = `1$1!${conf.name}^2!${conf.clazz}^3!${conf.number}}2$${conf.name}}${answers.join('}')}`
            let regx = /var rndnum="(\d+).(\d+)";/gim;
            let resy = regx.exec(ret.body)
            cb(null, {
                ok: true,
                code: ret.code,
                headers: {
                    'Cookie': cookies.join('; '),
                    'X-Requested-With': 'XMLHttpRequest'
                },
                form: { submitdata: encodeURIComponent(submitdata) },
                questions: questions,
                starttime: $("#starttime").val(),
                rn: `${resy[1]}.${resy[2]}`,
            })
        }).catch(function(err) {
            cb(err)
        })
    }
}

WJX.postAnswers = function(page) {
    return function(cb) {
        co(function*() {
            let f = {
                curid: conf.qid,
                starttime: page.starttime,
                hmt: '1',
                mst: '6000',
                // submit_text: '', // 验证码
                source: 'directphone',
                submittype: '1',
                rn: page.rn,
                rname: conf.name,
                t: Date.now()
            }
            let url = '/joinnew/processjq.ashx?' + querystring.stringify(f)
            console.log('地址:\n' + url)
            console.log('表单:\n' + page.form.submitdata)
            let ret = yield proxy.POST(url, page.headers, page.form)
            console.log(ret)
            let arr = []
            cb(null, arr)
        }).catch(function(err) {
            cb(err)
        })
    }
}

WJX.query = function(url) {
    return function(cb) {
        co(function*() {
            let ret = yield proxy.GET(url)
            let $ = cheerio.load(ret.body)
            let arr = []
            $('.data__items').each(function() {
                let topic = $(this).attr('topic')
                if (topic > 3) {
                    let question = $(this).find('.data__tit').text()
                    question = question.substr(question.indexOf('. ') + 2)
                    let answer = $(this).find('.data__key').text()
                    if (answer.indexOf('正确答案为：') != -1) {
                        answer = answer.split('正确答案为：')[1].trim()
                    } else {
                        answer = answer.split('（得分：')[0].trim().split('您的回答：')[1]
                    }
                    arr.push({
                        topic: topic,
                        question: question,
                        answer: answer,
                    })
                }
            })
            cb(null, arr)
        }).catch(function(err) {
            cb(err)
        })
    }
}

module.exports = WJX